<template>
  <section class="wrapper">
    <section class="info">
      <section class="img" :style="{backgroundImage: `url(${info.mainImg})`}">
        <section class="status" :class="{finish: currStatus !== 3}">{{ ['未开始', '已完结', '进行中'][currStatus - 1] }}</section>
      </section>
      <section class="text">
        <section class="title">
          {{ info.theme }}
          <section class="tag">{{ info.typeName }}</section>
        </section>
        <section class="time">
          <img src="../assets/images/time.png" alt="">
          {{ info.createTime | replace }} - {{ info.endTime | replace }}
        </section>
        <section class="introduce">
          {{ info.introduction }}
        </section>
      </section>
    </section>
    <section class="tabs">
      <section
        v-for="item in tabs"
        v-show="step > item.step || (step === 5 && item.step === 0)"
        :class="{active: currStep === item.step + 1}"
        @click="changeTab(item)"
      >
        {{ item.name }}
      </section>
    </section>
    <section class="content">
      <section class="content-tabs" v-if="currStep !== 2 && currStep !== 3">
        <a
          href="javascript:;"
          :class="{active: gameStage === tab.type}"
          v-for="tab in gameTabs" :key="tab.type"
          @click="gameStage = tab.type"
        >
          {{ tab.name }}
        </a>
      </section>
      <section v-show="currStep === 1" class="step-one step-item">
        <section v-if="currGameStage.notice" class="text" v-html="currGameStage.notice"/>
      </section>
      <section v-show="currStep === 2" class="step-two step-item">
        <section class="title">组队信息</section>
        <section class="game-info">
          <section>
            <span class="name">赛区：</span>
            <span class="value">北京</span>
          </section>
          <section>
            <span class="name">参赛形式：</span>
            <span class="value">团队</span>
          </section>
          <section>
            <span class="name">组别：</span>
            <span class="value">初中</span>
          </section>
          <section>
            <span class="name">团队名称：</span>
            <span class="value">未来科技</span>
          </section>
        </section>
        <section class="title">队员信息</section>
        <section class="member-list">
          <section class="member-item" v-for="user in userList">
            <section class="name">
              姓名：<span class="value">{{ user.memberName }}</span>
            </section>
            <section class="school">
              所在学校（就读学校）：<span class="value">{{ user.schoolName }}</span>
            </section>
          </section>
        </section>
        <section class="title">指导老师</section>
        <section class="game-info teacher-info">
          <section>
            <span class="name">姓名：</span>
            <span class="value">{{ teacher.memberName }}</span>
          </section>
          <section>
            <span class="name">工作单位：</span>
            <span class="value">{{ teacher.job }}</span>
          </section>
        </section>
      </section>
      <section v-show="currStep === 3" class="step-three step-item">
        <img src="../assets/images/works.png" alt="">
        <section class="work-text">请登录网站查看</section>
      </section>
      <section v-show="currStep === 4" class="step-four step-item">
        <section class="title">
					<img src="../assets/images/score.png" alt="">
					<section class="name">
						{{currGameStage.name}}比赛成绩
					</section>
<!--          <img src="../assets/images/trophy.png" alt="">-->
<!--          <section class="result">-->
<!--            <section class="name">本次比赛所得成绩为20.00分</section>-->
<!--            <section class="time">公布时间 202002:34</section>-->
<!--          </section>-->
        </section>
        <section class="appeal-btn" v-if="gameStage === 3 && isLeader">
					<a href="javascript:;" v-if="disabled" class="disabled">申诉？</a><a href="javascript:;" v-else @click="showAppealModal">申诉？</a>限比赛结果出来后2小时之内有效,<a :class="{disabled: disabled}" href="javascript:;" @click="getAppeal">查看结果</a>
        </section>
				<template v-if="scoreObj[currGameStage.id]">
					<table
						v-if="!isEmpty(scoreObj[currGameStage.id].reportCart)"
						class="layui-table"
						style="margin-bottom: 50px;"
					>
						<thead>
						<tr>
							<th v-for="head in paperHead">{{ head }}</th>
						</tr>
						</thead>
						<tbody>

						<tr v-for="item in scoreObj[saichengid].reportCart">
							<td>{{ item.memberName }}</td>
							<td>{{ item.points }}</td>
							<td>{{ item.createTime }}</td>
						</tr>
						</tbody>
					</table>
					<table
						v-if="!isEmpty(scoreObj[currGameStage.id].workScore)"
						class="layui-table">
						<thead>
						<tr>
							<th v-for="head in workHead">{{ head }}</th>
						</tr>
						</thead>
						<tbody>
						<tr>
							<td>{{ scoreObj[currGameStage.id].workScore.score }}</td>
							<td>{{ scoreObj[currGameStage.id].workScore.score1 }}</td>
							<td>{{ scoreObj[currGameStage.id].workScore.score2 }}</td>
						</tr>
						</tbody>
					</table>
				</template>
      </section>
    </section>
    <common-modal
      :visible.sync="showAppeal"
      title="申诉"
    >
      <textarea placeholder="请输入申诉原因（请仔细确认申诉信息，提交后不可更改）" v-model="appealText" cols="30" rows="10"></textarea>
      <template #footer>
        <a href="javascript:;" class="btn" @click="appeal">
          确认申诉
        </a>
      </template>
    </common-modal>
    <common-modal
      :visible.sync="showAppealResult"
      title="申诉"
    >
      <section class="desc">
        {{ appealResult }}
      </section>
    </common-modal>
  </section>
</template>
<script>
import {getTeamInfo, getMatchInfo, getAppeal, appeal} from '@/api/match'
export default {
  name: 'GameDetails',
  data: () => ({
    showAppeal: false,
    showModal: false,
    showAppealResult: false,
	  levelUp: false,
	  disabled: false,
    currStep: 1,
    step: 1,
    gameStage: 1,
    currStatus: '',
	  appealText: '',//申诉文字
	  appealResult: '',
    teacher: {},
	  scoreObj: {},
	  paperHead: [],
	  workHead: [],//表头
    userList: [],
    isMulti: false,
    saichengid:0,
    tabs: [
      {step: 0, name: '参赛须知'},
      {step: 1, name: '组队信息'},
      {step: 2, name: '提交作品'},
      {step: 3, name: '比赛结果'}
    ],
    gameInfo: {
      chedulesList: [],
      tmatch: {
        createTime: '',
        endTime: '',
      }
    },
	  userInfo: {},
	  teamInfo: {},
    info: {},
  }),
  computed: {

	  isLeader() {
		  if (!this.userList) return
		  return this.userInfo && this.userInfo.id === (this.userList.filter(item => item.roleType === 2)[0] || {}).userId
	  },
    gameTabs() {
    //  alert(JSON.stringify(this.gameInfo.chedulesList))
      const list = this.gameInfo.chedulesList || []
	    var index = list.findIndex(item => item.schedule.id === this.teamInfo.scheduleId)
	    if (this.teamInfo.matchId !== parseInt(this.$route.params.id)) index = 0
	    return list.slice(0, index + 1).map(function (item, itemIndex) {
        const schedule = item.schedule
        return {
	        id: schedule.id,
	        endTime: schedule.endTime,
	        isView: itemIndex < index || list.length === 4,
	        type: schedule.scheduleType,
	        name: schedule.scheduleName,
	        notice: schedule.notice,
	        scheduleItem: item.scheduleItem || []
        }
      })
    },
    currGameStage() {
      //alert(this.gameStage)
      this.saichengid=this.gameInfo.chedulesList[this.gameStage-1].schedule.id
	    return this.gameTabs.find(e => e.type === this.gameStage) || {}
    }
  },
  created() {
  	this.userInfo = this.$storage.getData('userInfo')
	  this.$route.meta.title = this.info.name
    this.getMatchData()
    this.getTeamInfo()
  },
  methods: {
    getMatchData() {
      const date = +new Date()
      getMatchInfo({id: this.$route.params.id}).then(res => {
        this.info = res.tmatch
        this.isMulti = this.info.multiplayer === 1
        this.gameInfo = res
        // this.step = this.gameInfo.tmatch.state + 1
        var startDate = +new Date(this.gameInfo.tmatch.createTime)
        var endDate = +new Date(this.gameInfo.tmatch.endTime)
        if (date < startDate) this.currStatus = 1 //未开始
        else if (date > endDate) this.currStatus = 2 //已结束
        else this.currStatus = 3 //进行中
        this.gameInfo.chedulesList = this.gameInfo.chedulesList || []
      })
    },
    getTeamInfo() {
      getTeamInfo(this.$route.params.id).then(data => {
        console.log(JSON.stringify(data))
        if (data.teamInfo && data.teamInfo.matchId === parseInt(this.$route.params.id)) {
          this.teamInfo = data.teamInfo

          // 通过teamList进行过滤到队员信息
          this.userList = data.teamList.filter(item => item.roleType === 0 || item.roleType === 2)
          // 通过teamList进行过滤获取到教师信息
          this.teacher = data.teamList.filter(item => item.roleType === 1)[0] || {}
          this.step = data.teamInfo.state + 1
	        this.workHead = data.workHead || []
	        this.paperHead = data.paperHead || []
          console.log(this.paperHead )
	        this.$set(this.scoreObj, this.teamInfo.scheduleId, {
		        workScore: data.workScore || {},
		        reportCart: data.reportCart || []
	        })
          console.log(this.scoreObj)
	        if (data.history && data.history.length > 0) {
		        data.history.forEach(item => {
			        this.$set(this.scoreObj, item.scheduleId, {
				        workScore: item.workScore || {},
				        reportCart: item.reportCart || []
			        })
		        })
	        }
          console.log(JSON.stringify(this.scoreObj))
	        this.levelUp = data.levelUp
	        this.disabled = this.isEmpty(data.workScore) || ((+new Date() - (+new Date(data.workScore.createTime))) / 1000 / 60 / 60) > 2
	        if (data.workScore || data.reportCart || data.history.length > 0){
		        this.step = 4
	        }
          // 步骤到第二步
        }else{
          this.step = 1
        }
      })
    },
	  isEmpty(obj) {
		  if (!obj) return true
		  if (typeof obj.length === 'number') return obj.length === 0
		  var result = []
		  for (var k in obj) {
			  result.push(k)
		  }
		  return result.length === 0
	  },
	  appeal() {
		  if (!this.appealText.trim()) return layer.msg('请输入申诉内容', {icon: 2})
		  appeal({content: this.appealText.trim()}).then(() => {
			  layer.msg('提交申诉成功！', {icon: 1})
			  setTimeout(() => {
				  this.showAppeal = false
				  this.appealText = ''
			  }, 1500)
			})
		},
	  showAppealModal() {
		  getAppeal().then(data => {
			  if (data && data.content) layer.msg('您已提交申诉。', {icon: 5})
			  else this.showAppeal = true
			})
	  },
	  getAppeal() {
		  if (this.disabled) return
		  getAppeal().then(res => {
			  this.showAppealResult = true
			  this.appealResult = res ? res.remark : '请耐心等待回复'
		  })
	  },
    changeTab: function (item) {//切换tab
      this.currStep = item.step + 1
    }
  }
}
</script>
<style lang="less" scoped>
  .flex {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .info {
    margin-bottom: 0.267rem;
    background-color: #ffffff;
    box-shadow: 0 0 0.2rem 0.04rem rgba(0, 0, 0, 0.02);
    border-radius: 0.133rem;

    .img {
      margin-bottom: 0.133rem;
      position: relative;
      height: 4.693rem;
      background-color: #5b666d;
      -webkit-background-size: cover;
      background-position: center 0;
      background-size: cover;

      .status {
        position: absolute;
        left: 0.533rem;
        top: 0.533rem;
        .flex;
        justify-content: center;
        padding: 0 0.133rem;
        height: 0.533rem;
        font-size: 0.293rem;
        font-weight: bold;
        color: #ffffff;
        border: 2px solid #fff;
        background-image: linear-gradient(250deg,
        #ffbb5b 0%,
        #f78b2e 100%),
        linear-gradient(
          #e5f5ff,
          #e5f5ff);
        color: #ffffff;
        border-radius: 0.267rem;

        &.finish {
          color: #fff;
          background-image: linear-gradient(250deg,
          #007eff 0%,
          #30a4ed 100%),
          linear-gradient(
            #e5f5ff,
            #e5f5ff);
        }
      }
    }

    .text {
      padding: 0.4rem;

      .title {
        margin-bottom: 0.24rem;
        .flex;
        justify-content: flex-start;
        font-size: 0.373rem;
        font-weight: 500;
        color: #000000;

        .tag {
          .flex;
          margin-left: 0.267rem;
          padding: 0 0.053rem;
          background-color: #e5eaf1;
          border-radius: 0.04rem;
          height: 0.4rem;
          font-size: 0.293rem;
          color: #6b7686;
        }
      }

      .time {
        margin-bottom: 0.4rem;
        .flex;
        justify-content: flex-start;
        font-size: 0.32rem;
        color: #666666;

        img {
          margin-right: 0.133rem;
        }
      }

      .introduce {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        font-size: 0.347rem;
        line-height: 0.64rem;
        color: #666666;
      }
    }
  }

  .tabs {
    .flex;
    min-height: 1.28rem;
    background-color: #ffffff;
    justify-content: flex-start;
    section {
      position: relative;
      width: 25%;
      .flex;
      height: 1.28rem;
      font-size: 0.347rem;
      color: #333333;

      &.active {
        color: #007eff;

        &::after {
          width: 100%;
          content: '';
          height: 0.053rem;
          background: #148eff;
          position: absolute;
          left: 0;
          bottom: 0;
        }
      }
    }
  }

  .content {
    padding: 0.4rem;
    padding-bottom: 1.33rem;
    background: #fff;
		.content-tabs {
      margin-bottom: 0.507rem;
      .flex;
      display: inline-flex;
      height: 0.933rem;
      border-radius: 0.04rem;
      border: solid 1px #e5e5e5;

      a {
        width: 1.6rem;
        .flex;
        height: 100%;
        font-size: 0.347rem;
        color: #666666;

        &.active {
          background: #e1e7ec;
          color: #148eff
        }
      }
    }

    .step-item {
      .text {
        margin-top: 0.4rem;
        overflow: auto;
        font-size: 0.32rem;
        line-height: 0.64rem;
        color: #374b5d;
      }
    }

    .step-two {
      .title {
        margin-bottom: 0.4rem;
        color: #374b5d;
        font-weight: bold;
        font-size: 0.373rem;
      }

      .value {
        color: #0388f7;
      }

      .game-info {
        margin-bottom: 0.667rem;
        font-size: 0.32rem;
        color: #666;

        & > section {
          margin-bottom: 0.133rem;
        }
      }

      .member-list {
        margin-bottom: 0.293rem;

        .member-item {
          margin-bottom: 0.267rem;
          padding: 0.213rem 0.28rem;
          background-color: #ffffff;
          font-size: 0.32rem;
          color: #333;
          background-color: #ffffff;
          box-shadow: 0rem 0rem 0.12rem 0rem rgba(57, 63, 69, 0.14);
          border-radius: 0.04rem;

          .school {
            .flex;

            .value {
              flex: 1;
              overflow: hidden;
              -ms-text-overflow: ellipsis;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          & > section {
            margin-bottom: 10px;
          }

          &:last-of-type {
            margin-right: 0;
          }

        }
      }
    }

    .step-three {
      padding: 1.6rem;
      .flex;
      flex-direction: column;
      justify-content: center;

      img {
        width: 6.507rem;
      }

      .work-text {
        margin-top: 1.2rem;
        font-size: 0.373rem;
        font-weight: bold;
        color: #374b5d;
      }
    }

    .step-four {
      .title {
        .flex;
        justify-content: flex-start;
        margin-bottom: 0.667rem;
        color: #333;
        margin-right: 0.133rem;
				.name {
					margin-left: 0.267rem;
					font-size: 0.373rem;
					font-weight: 500;
					color: #333333;
				}
        .result {
          .name {
            margin-bottom: 0.16rem;
            font-size: 0.373rem;
            font-weight: 500;
            color: #333333;
          }

          .time {
            font-size: 0.347rem;
            color: #666666;
          }
        }
      }

      .appeal-btn {
        .flex;
        padding: 0.267rem 0;
        height: 1.067rem;
        font-size: 0.347rem;
        background-color: #e5f3ff;
        border-radius: 3px;

        a {
          color: #0388f7;
					&.disabled {
						color: #ccc;
						cursor: not-allowed;
					}
        }
      }
    }

    textarea, .desc {
      margin-bottom: 0.4rem;
      padding: 0.213rem 0.307rem;
      width: 100%;
      height: 2.667rem;
      background-color: #eeeeee;
      border: none;
      outline: none;
      font-size: 0.347rem;
      color: #767676;
    }

    .desc {
      height: auto;
    }
  }
</style>
